/**
 * 
 */
package kr.pe.johnkim.dayve.activity;

import java.util.List;

import kr.pe.johnkim.dayve.util.DayveCommon;
import kr.pe.johnkim.dayve.util.ExternalJoinConstant;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

/**
 * @author johnkim
 *
 */
public class DayveFacebookView extends Activity {
	
	public static String TAG = DayveFacebookView.class.getSimpleName();
	
	DayveCommon dayveCommon = new DayveCommon();
	
	private Facebook mFacebook = new Facebook(ExternalJoinConstant.FACEBOOK_APP_ID);

	private String mFacebookAccessToken;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mFacebookAccessToken = DayveCommon.getAppPreferences(this, "ACCESS_TOKEN");
		//mFacebook.setAccessToken(mFacebookAccessToken);

		login();

	}

	/**
	 * Facebook 에 로그인을 한다.
	 */
	public void login() {
//		Toast.makeText(getApplicationContext(), "login : " + mFacebookAccessToken, Toast.LENGTH_SHORT).show();
		
		Log.i(TAG, "login");

		try {
			if (!"".equals(mFacebookAccessToken) && mFacebookAccessToken != null) {
				
				Log.i(TAG, "mFacebookAccessToken is available");
				
				mFacebook.setAccessToken(mFacebookAccessToken);
				
				String resultStr = mFacebook.request("me");      
				JSONObject jo = new JSONObject(resultStr);
				jo.getString("id");		
				
				feed();
				
				// main thread 에서 child thread 를 호출 한다.
//				Thread thread = new Thread(null, feedBackgroundThreadProcessing, "Background_feed");
//				thread.start();
			} else {
				Log.i(TAG, "mFacebookAccessToken is not available");
				
				mFacebook.authorize2(this, new String[] {"publish_stream, user_photos, email"}, new AuthorizeListener());
			}
		} catch (JSONException je) {
			mFacebook.authorize2(this, new String[] {"publish_stream, user_photos, email"}, new AuthorizeListener());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Toast.makeText(getApplicationContext(), "onActivityResult", Toast.LENGTH_SHORT).show();
		
		if (resultCode == RESULT_OK) {
			if (requestCode == ExternalJoinConstant.FACEBOOK_AUTH_CODE) {
				mFacebook.authorizeCallback(requestCode, resultCode, data);
			}
		} else {
			if (requestCode == ExternalJoinConstant.FACEBOOK_AUTH_CODE) {
				Toast.makeText(getApplicationContext(), "FACEBOOK_AUTH_CODE : " + mFacebookAccessToken, Toast.LENGTH_SHORT).show();
				mFacebook.authorizeCallback(requestCode, resultCode, data);
			}      
		}
	}

	
	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		
		finish();
	}
	
	/* 최상위 프로세스가 아닐 경우 프로세스를 종료 한다.
	 * 
	 * => Home Key 를 눌렀을때 프로세스를 종료 한다.
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if(!isForegrdound()) {
//			System.exit(0);
		}
	}
	
	/**
	 * 현재 프로세스가 최상위로 실행중인지 검사 한다.
	 * 
	 * true : 최상위
	 * 
	 * @return
	 */
	public boolean isForegrdound() {
	    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> list = am.getRunningTasks(1);
	    ComponentName cn = list.get(0).topActivity;
	    String name = cn.getPackageName();
	     
	    return name.indexOf(getPackageName()) > -1;
	}

	/**
	 * Facebook 에 글과 사진을 올린다.
	 */
	private void feed() {
		Log.i(TAG, "feed");
		
		try { 
			Intent mIntent = getIntent();
			
			String content = mIntent.getStringExtra("content");
			String link = mIntent.getStringExtra("link");
			byte[] photoBytes = mIntent.getByteArrayExtra("photoBytes");
			
			Log.e(TAG, "> content : " + content);
			Log.e(TAG, "> link    : " + link);
			
			Bundle params = new Bundle();
			
			params.putString("message", content);            
			params.putString("source", link);
			params.putByteArray("source", photoBytes);
			
			String resultStr = mFacebook.request("me/photos", params, "POST");

			JSONObject jo = new JSONObject(resultStr);

			jo.getString("id");

			setResult(RESULT_OK);
			
//			Toast.makeText(getApplicationContext(), "페이스북 포스팅에 성공했습니다.", Toast.LENGTH_LONG).show();
			
			successPostToast();
			
//			DayveCategoryAnalysisView.RESULT_FACEBOOK_POSTING = "SUCCESS";
//			
//			Intent i = new Intent();
//			setResult(RESULT_OK, i);
//			
//			finish();
		} catch (Exception e) {
			setResult(RESULT_CANCELED);
//			Toast.makeText(getApplicationContext(), "페이스북 포스팅에 실패했습니다." + "\n" + "다시 시도해 보시기 바랍니다.", Toast.LENGTH_LONG).show();
			
			failPostToast();
			
//			DayveCategoryAnalysisView.RESULT_FACEBOOK_POSTING = "SUCCESS";
//			
//			Intent i = new Intent();
//			setResult(RESULT_OK, i);
//			
//			finish();
		}
		
		/**
		 * Facebook Posting 이 호출되면 결과에 상관없이 SUCCESS 를 세팅해서
		 * onActivityResult 에 영향이 미치지 않도록 한다.
		 */
		DayveCategoryAnalysisView.RESULT_FACEBOOK_POSTING = "SUCCESS";
		
		Intent i = new Intent();
		setResult(RESULT_OK, i);
		
		finish();
	}
	
	private void successPostToast() {
		CharSequence text = getResources().getString(R.string.facebook_success_posting);
		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}
	
	private void failPostToast() {
		CharSequence text = getResources().getString(R.string.facebook_fail_posting_01) + "\n" + getResources().getString(R.string.facebook_fail_posting_02);
		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}
	
	private Runnable feedBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
			// TODO Auto-generated method stub
			feed();
		}
	};


	/**
	 * Facebook 인증후 처리를 위한 callback class 이다.
	 *
	 * @author John_Kim <cale9797@gmail.com>
	 *
	 */
	public class AuthorizeListener implements DialogListener {
//		@Override
		public void onCancel() {
			// TODO Auto-generated method stub

		}

//		@Override
		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
//			Toast.makeText(getApplicationContext(), "onComplete : " + mFacebookAccessToken, Toast.LENGTH_LONG).show();
			mFacebookAccessToken = mFacebook.getAccessToken();
			DayveCommon.setAppPreferences(DayveFacebookView.this, "ACCESS_TOKEN", mFacebookAccessToken);      
			feed();
		}

//		@Override
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
		}

//		@Override
		public void onFacebookError(FacebookError e) {
			// TODO Auto-generated method stub
		}

	}
}
